const storageService = require('../../../services/storage')

// 获取 App 实例
const appInstance = getApp();
Component({
  properties: {
    group: {
      type: Object,
      value: {
        deviceId: '',
        totalSwitch: false,
        name: '设备编组',
        status: '当前行程',
        power: false,
        startTime: '--:--',
        endTime: '--:--',
        //bluetoothStatus: '01', // 蓝牙状态：00-未连接，01-已连接
        //wifiStatus: '03', // WiFi状态：02-未连接，03-已连接
        //fanStatus: '07', // 风扇状态：06-未启动，07-已启动
        deviceIds: [], // 编组内的设备ID列表
        onlines: [],
      },
      observer: function (newVal, oldVal) {
        if (newVal) {
          console.log("observer", newVal)
          // 基本检查，确保 newVal 是一个有效的编组对象
          // 在属性变化时，重新加载通道配置
          // console.log(`编组卡片 observer: group prop changed for ID ${newVal.id}`);
        }
      }
    },
    index: {
      type: Number,
      value: 0,
    },
    isGroupCard: {
      type: Boolean,
      value: true,
    },
  },

  data: {
    longPressThreshold: 3000, // 长按阈值3秒
    channelConfigLastUpdate: 0, // 用于跟踪通道配置最后更新时间
    getValInterval: null,
    channels: [],
    lastTapTime: 0,
    lastTapTimestamp: 0, // 用于记录上一次点击的时间戳
    singleTapTimer: null,
  },

  lifetimes: {
    attached() {
      console.log("attached...")
      const $t = this;
      const did = this.data.group.deviceId
      const isManualMode = storageService.isManualModeState(did)
      let valArr = []
      if (isManualMode) {
        valArr = storageService.getLastManualVal(did)
      } else {
        //TODO计算自动模式理论进度
      }
      const valLen = valArr.length
      let arr = storageService.getDeviceChannels(did)
      for (var i = 0; i < arr.length; i++) {
        if (valLen > i) {
          arr[i].v = parseInt(valArr[i])
          arr[i].barv = arr[i].v > 5 ? arr[i].v : 5
        } else {
          arr[i].v = 0
          arr[i].barv = 5
        }
      }
      this.setData({
        channels: arr
      })


    },

    detached() {
      clearTimeout(this.data.singleTapTimer);
      this.data.singleTapTimer = null;
    }
  },

  methods: {
    initVal(obj) {
      let valArr = obj.msg.split(';');
      for (var i = 0; i < this.data.channels.length; i++) {
        if (valArr.length > i) {
          this.data.channels[i].v = parseInt(valArr[i]);
          this.data.channels[i].barv = this.data.channels[i].v > 5 ? this.data.channels[i].v : 5;
        }
      }
      this.setData({
        channels: this.data.channels
      })
    },


    // 切换总开关状态
    toggleSwitch(e) {
      const currentTime = e.timeStamp;
      const timeDiff = currentTime - this.data.lastTapTime;

      if (timeDiff > 0 && timeDiff < 300) {
        // 双击事件
        this.doubleTapAction(e);
        this.setData({
          lastTapTime: 0
        }); // 重置，防止三击误判
      } else {
        // 第一次点击或超时，记录时间并设置定时器等待第二次点击
        this.setData({
          lastTapTime: currentTime
        });

        // 延迟执行单击操作，若在延迟期内有第二次点击则取消单击
        this.data.singleTapTimer = setTimeout(() => {
          if (this.data.lastTapTime === currentTime) { // 确保仍是第一次点击的记录
            this.singleTapAction(e); // 执行单击逻辑
          }
        }, 300);
      }
    },

    // 长按设备卡片处理（删除编组）
    handleLongPress(e) {
      if (
        e.target.dataset.type === 'total' ||
        e.target.dataset.type === 'name'
      ) {
        return
      }
      wx.showModal({
        title: '删除编组',
        content: '确定要删除此编组吗？（不会删除编组内设备）',
        success: res => {
          if (res.confirm) {
            this.triggerEvent('deleteGroup', {
              index: this.data.index
            })
          }
        },
      })
    },

    // 长按设备名称处理（修改名称）
    handleNameLongPress(e) {
      wx.showModal({
        title: '修改编组名称',
        content: '',
        editable: true,
        placeholderText: '请输入新的编组名称',
        success: res => {
          if (res.confirm && res.content) {
            const device = storageService.getDeviceInfo(this.data.group.deviceId)
            if (device != null) {
              device.name = res.content
              storageService.saveDeviceInfo(this.data.group.deviceId, device)
              this.setData({
                'group.name': res.content,
              })
              this.triggerEvent('nameChange', {
                index: this.data.index,
                name: res.content,
              })
            } else {
              wx.showToast({
                title: '修改名称失败',
                icon: 'none',
              })
            }
          }
        },
      })
    },

    // 点击设备卡片跳转到模式设置页面
    navigateToModeSetting(e) {
      if (
        e.target.dataset.type === 'total' ||
        e.target.dataset.type === 'name'
      ) {
        return
      }
      wx.navigateTo({
        url: `/packageSeahwaterDiy/pages/mode_setting/mode_setting?did=${this.data.group.deviceId}`,
      })
    },

    // 跳转到编组设备页面
    navigateToGroupDevices() {
      wx.navigateTo({
        url: `/packageGroup/pages/group_devices/group_devices?did=${this.data.group.deviceId}`,
      })
    },

    singleTapAction(e) {
      const type = e.currentTarget.dataset.type
      const newValue = !this.data.group.totalSwitch
      const hasValue = this.data.group.onlines.includes(0)
      if (hasValue) {
        wx.showToast({
          title: '设备未全在线，操作失败!',
          icon: 'none',
        })
        return
      }
      this.triggerEvent('switchchange', {
        type,
        value: newValue,
        index: this.data.index,
      })
    },
    doubleTapAction(e) {
      clearTimeout(this.data.singleTapTimer); // 清除可能存在的单击定时器
      const type = e.currentTarget.dataset.type
      const newValue = !this.data.group.totalSwitch
      const hasValue = this.data.group.onlines.includes(0)
      if (hasValue) {
        wx.showToast({
          title: '设备未全在线，操作失败!',
          icon: 'none',
        })
        return
      }
      this.triggerEvent('switchDbchange', {
        type,
        value: newValue,
        index: this.data.index,
      })
    },






  },
})